/*
 * @Author: hongbin
 * @Date: 2022-11-03 12:20:04
 * @LastEditors: hongbin
 * @LastEditTime: 2022-11-03 13:54:11
 * @Description:mongodb
 */
import { MongoClient, Db } from "mongodb";

const options = {
    host: "159.75.22.82",
    port: "27017",
    db_name: "MetaCommunity",
};

const MongoClientConfig = {
    useUnifiedTopology: true,
    auth: {
        username: "hongbin",
        password: "Hongbin",
    },
};

//TODO 连接字符串 和  MongoClientConfig 放到全局变量中
// const uri = process.env.MONGODB_URI;
const uri = `mongodb://${options.host}:${options.port}/${options.db_name}`;

export let clientPromise: Promise<MongoClient>;

let db: Db;

const DB: Promise<Db> = new Promise((resolve, reject) => {
    if (db) resolve(db);
    console.log("连接..");
    if (!uri) {
        reject(new Error("没有连接字符串"));
    } else {
        const client = new MongoClient(uri, MongoClientConfig);
        clientPromise = client.connect();
        clientPromise.then((client) => {
            console.log("连接mongodb成功");
            db = client.db();
            resolve(db);
        });
    }
});

export default DB;
